package top.ooyyh.bytheway.aspect;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import top.ooyyh.bytheway.annotation.NeedAuthorization;
import top.ooyyh.bytheway.mapper.PowerMapper;
import top.ooyyh.bytheway.mapper.UserMapper;
import top.ooyyh.bytheway.utils.JwtUtils;
import top.ooyyh.bytheway.utils.Result;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Aspect
@Component
public class NeedAuthorizationAspect {

    @Autowired
    UserMapper userMapper;
    @Autowired
    PowerMapper powerMapper;

    @Pointcut("@annotation(top.ooyyh.bytheway.annotation.NeedAuthorization)")
    public void auth() {}

    @Around("auth()")
    public Object checkAuth(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取请求
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            return Result.error("无法获取请求上下文");
        }
        HttpServletRequest request = attributes.getRequest();

        String router = request.getRequestURI();

        // 获取 token
        String authHeader = request.getHeader("Authorization");
        if (authHeader == null) {
            return Result.error("缺少 Authorization 头");
        }

        String token;
        if (authHeader.startsWith("Bearer ")) {
            token = authHeader.substring(7);
        } else {
            token = authHeader;
        }

        String username;
        try {
            username = (String) JwtUtils.parseToken(token).get("username");
        } catch (Exception e) {
            return Result.error("无效的 Token");
        }

        // 获取方法名（做权限匹配用）
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        String methodName = signature.getMethod().getName();
        //Refactor
        List<String> userPower = userMapper.getUserPower(username);
        List<String> requiredPower = powerMapper.getRouterPower(router);

        if (!userPower.containsAll(requiredPower)) {
            return Result.error("权限不足");
        }

        // 有权限，继续执行原方法
        return joinPoint.proceed();
    }

}
